const express = require('express');
const axios = require('axios');
const app = express();
const mysql = require('mysql');
const formatTime = require('./utils/filterTime.js')

app.use(express.json());
const appid = 'wx4652f206cab94820'
const secret = '80c4d326be7d9dbafd0949a13960b9e5'
const port = 8888;
const service = axios.create({
    // baseURL: import.meta.env.VITE_APP_BASE_API, //基础路径
    timeout: 3 * 60 * 1000 // request timeout
})
//设置跨域访问
app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1');
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

const newError = function (message, next, status = 500) {
    const error = new Error(message);
    error.status = status;
    return next(error);
};



// 配置数据库连接参数
const connection = mysql.createConnection({
    host: '8.155.29.29', // 数据库地址
    user: 'admin', // 数据库用户
    password: 'LF-qazedc2580', // 数据库密码
    database: 'csData' // 数据库名
    // database: 'zsData' // 数据库名
});

// 开启数据库连接
connection.connect((err) => {
    if (err) {
        console.log('连接失败'); userInfo
        return
    }
    console.log('连接成功');

});



//获取token
const tokenFun = () => {
    return axios({
        url: 'https://api.weixin.qq.com/cgi-bin/token',
        method: 'get',
        params: {
            grant_type: 'client_credential',
            appid: 'wx4652f206cab94820',
            secret: '80c4d326be7d9dbafd0949a13960b9e5'
        }
    })
    // .then(data => {
    //     console.log(data, '555555');
    //     res.json(data.data)
    // }).catch((err) => {
    //     console.log(err, '554555');
    // })
}

//获取openid
app.get('/gwsj/getOpenid', (req, res) => {
    const { code } = req.query
    axios({
        url: `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}`,
        method: 'get',
    })
        .then(data => {
            res.json(data.data)
        }).catch((err) => {
            console.log(err, '554555');
        })
})

//登录注册
app.post('/gwsj/login', async ({ body }, res, next) => {
    try {
        const { nickName, avatarUrl, openid } = body
        const insertValues = {
            createDate: formatTime.default(new Date()),
            nickName,
            avatarUrl,
            openid,
            integral: 0,
            totalSession: 0,
            recordId: 0,
            recordList: JSON.stringify([])
        }
        // 要检查的条件
        const checkValues = {
            openid
        };
        const whereClause = Object.keys(checkValues).map(key => `${key} = '${checkValues[key]}'`).join(' AND ');
        // 执行查询
        connection.query(`SELECT * FROM user WHERE ${whereClause}`, (error, results, fields) => {
            if (results && !results.length) {
                const values = Object.values(insertValues).map(value => `'${value}'`).join(', ');
                connection.query(`INSERT INTO user (${Object.keys(insertValues).join(', ')}) VALUES (${values})`, function (error, info) {
                    insertValues.recordList = []
                    return res.json(insertValues)
                });
            } else {
                results[0].recordList = JSON.parse(results[0].recordList)
                return res.json(results[0])
            }
            if (error) {
                newError(error, next)
            }
        });
    } catch (error) {
        newError(error, next)
    }
})

//获取用户信息
app.get('/gwsj/userInfo', async ({ query }, res, next) => {
    const { openid } = query;
    connection.query(`SELECT * FROM user WHERE openid = '${openid}'`, (error, results, fields) => {
        if (results && results.length) {
            res.json({ ...results[0], recordList: JSON.parse(results[0].recordList) })
        } else {
            newError('查无此人', next, 400)
        }

    })
});

//修改用户信息
app.put('/gwsj/userInfo', async ({ body }, res, next) => {
    const { openid, nickName, avatarUrl } = body;
    // 执行UPDATE语句
    connection.query(`UPDATE user SET nickName = ?, avatarUrl = ? WHERE openid = ?`, [nickName, avatarUrl, openid], function (error, results, fields) {
        if (error) {
            newError(error, next)
        } else {
            res.json(results)
        }
    });
});

//获取手机号
app.post('/gwsj/getPhone', async (req, res) => {
    const { data: { access_token } } = await tokenFun()
    const { code } = req.body;
    axios({
        url: 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=' + access_token,
        method: 'get',
        data: {
            code
        }
    }).then(data => {
        res.json(data.data)
    }).catch((err) => {
        console.log(err, '554555');

    })
});



//获取小程序码
app.post('/gwsj/codeImg', async (req, res, next) => {
    const { scene, check_path, env_version, page } = req.body;
    const { data: { access_token } } = await tokenFun()
    service({
        url: 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' + access_token,
        method: 'post',
        responseType: 'arraybuffer',
        data: {
            scene,
            env_version,
            page,
            check_path
        }
    }).then(data => {
        res.json(data.data)
    }).catch((err) => {
        newError(error, next)
    })
});

//添加开房记录------------------------------------------------
app.post('/gwsj/addRecord', async ({ body }, res, next) => {
    try {
        const {
            openid,
            nickName,
            avatarUrl,
        } = body
        const dataInfo = {
            createName: nickName,
            createId: openid,
            createDate: formatTime.default(new Date()),
            avatarUrl,
            recordList: JSON.stringify([]),
            userList: JSON.stringify([{
                nickName,
                avatarUrl,
                newIntegral: 0,
                openid
            }]),
            status: 1, //1进心中0结束
            codeImg: ''
        }
        const values = Object.values(dataInfo).map(value => `'${value}'`).join(', ');
        connection.query(`INSERT INTO record (${Object.keys(dataInfo).join(', ')}) VALUES (${values})`, function (error, info) {
            if (error) {
                newError(error, next)

            } else {
                connection.query(`UPDATE user SET recordId = ? WHERE openid = ?`, [info.insertId, openid], function (error, results, fields) {
                    if (error) {
                        newError(error, next)

                    } else {
                        return res.json({ id: info.insertId })
                    }
                });
            }
        });
    } catch (error) {
        newError(error, next)

    }

})

//获取房间信息
app.get('/gwsj/getRecord', async ({ query }, res, next) => {
    const { id } = query;
    connection.query(`SELECT * FROM record WHERE id = '${id}'`, (error, results, fields) => {
        if (results && results.length) {
            const data = results[0]
            const userList = JSON.parse(data.userList)
            userList.forEach((its, index) => {
                connection.query(`SELECT * FROM user WHERE openid = '${its.openid}'`, (error, results, fields) => {
                    const { nickName, avatarUrl } = results[0]
                    its.nickName = nickName
                    its.avatarUrl = avatarUrl
                    if (userList.length == index + 1) {
                        res.json({ ...data, userList, recordList: JSON.parse(data.recordList) })
                    }
                    if (error) {
                        newError(error, next)

                    }
                })
            })
        } else {
            newError(error, next)
        }

    })
});

//修改房间信息
app.put('/gwsj/putRecord', async ({ body }, res, next) => {
    const { id, recordList, userList, codeImg } = body;
    // 执行UPDATE语句
    connection.query(`UPDATE record SET recordList = ?, userList = ?, codeImg = ? WHERE id = ?`, [JSON.stringify(recordList), JSON.stringify(userList), codeImg, id], function (error, results, fields) {
        if (error) {
            newError(error, next)
        } else {
            res.json(results)
        }
    });
});

//转账
app.put('/gwsj/payMoney', async ({ body }, res, next) => {
    const { recordId, nickName, payMoney, createDate, payName, payId, openid } = body;
    connection.query(`SELECT * FROM record WHERE id = '${recordId}'`, (error, results, fields) => {
        if (error) {
            newError(error, next)
        }
        const old = results[0]
        old.recordList = JSON.parse(old.recordList)
        old.userList = JSON.parse(old.userList)
        old.recordList.push({
            nickName,
            payMoney,
            recordId,
            createDate,
            payName,
            payId
        })
        old.userList.forEach((item) => {
            if (item.openid == payId) {
                item.newIntegral += Number(payMoney);
            }
            if (item.openid == openid) {
                item.newIntegral -= Number(payMoney);
            }
        });
        // 执行UPDATE语句
        connection.query(`UPDATE record SET recordList = ?, userList = ? WHERE id = ?`, [JSON.stringify(old.recordList), JSON.stringify(old.userList), recordId], function (error, results, fields) {
            if (error) {
                newError(error, next)
            } else {
                res.json(results)
            }
        });
    })
});

//结束房间信息
app.put('/gwsj/endRecord', async ({ body }, res, next) => {
    const { id, userList, createDate } = body;
    connection.query(`UPDATE record SET status = ? WHERE id = ?`, [0, id], function (error, results, fields) {
        if (error) {
            newError(error, next)
        } else {
            userList.forEach((item, index) => {
                // 执行UPDATE语句
                connection.query(`SELECT * FROM user WHERE openid = '${item.openid}'`, (error, results, fields) => {
                    if (error) {
                        newError(error, next)
                    }
                    const info = results[0];
                    info.recordList = JSON.parse(info.recordList);
                    info.integral = Number(item.newIntegral) + Number(info.integral);
                    info.totalSession = Number(info.totalSession) + 1;
                    info.recordList.push({ recordId: id, createDate, newIntegral: Number(item.newIntegral) })
                    connection.query(`UPDATE user SET integral = ?, recordList = ?,totalSession = ? WHERE openid = ?`, [info.integral, JSON.stringify(info.recordList), info.totalSession, item.openid], function (error, results, fields) {
                        if (error) {
                            newError(error, next)

                        } else {
                            if (userList.length == index + 1) {
                                res.json({})
                            }
                        }
                    });
                })
            });
        }
    });

});

app.listen(port, () => {
    console.log(`Server is running at http://localhost:${port}`);
});

app.use((err, req, res, next) => {
    res.status(err.status || 500);
    res.json({
        error: {
            message: err.message
        }
    });
});


